const express = require('express')
const fse = require('fs-extra')
const path = require('path')
const cors = require('cors')
const multer = require('multer')
const upload = multer({ dest: 'uploads' })

const app = express()

app.use(cors())

// 配置这个中间件后，可以解析json格式的数据，req.body就可以访问到了
app.use(express.json())
// 配置这个中间件后，可以解析表单url-encodeed的数据，req.body就可以访问到了
app.use(express.urlencoded({ extended: true }))

const UPLOAD_DIR = path.resolve(__dirname, 'uploads'); // 上传文件存储目录
fse.ensureDirSync(UPLOAD_DIR); // 确保上传目录存在

const mergeChunks = async (filename, totalChunks) => {
  const chunkDir = path.resolve(UPLOAD_DIR, `chunks_${filename}`)
  const filePath = path.resolve(UPLOAD_DIR, filename)

  fse.ensureFileSync(filePath)
  const writeStream = fse.createWriteStream(filePath)

  for (let i = 0; i < totalChunks; i++) {
    const chunkFilePath = path.join(chunkDir, `${filename}-chunk-${i}`);
    const data = await fse.readFile(chunkFilePath);
    writeStream.write(data);
    await fse.remove(chunkFilePath);
  }

  writeStream.end();
  await fse.remove(chunkDir)
}

app.post('/upload', upload.single('file'), async (req, res) => {
  const { filename, currentChunk, totalChunks } = req.body
  const file = req.file

  const chunkDir = path.resolve(UPLOAD_DIR, `chunks_${filename}`)
  fse.ensureDir(chunkDir)

  const chunkFilePath = path.resolve(chunkDir, `${filename}-chunk-${currentChunk}`)
  fse.moveSync(file.path, chunkFilePath)

  if (+currentChunk + 1 === +totalChunks) {
    await mergeChunks(filename, totalChunks);
    res.send({ message: 'File upload complete', url: `/uploads/${filename}` })
  } else {
    res.send({ message: `Chunk ${chunkNumber} uploaded` })
  }
})

app.listen(3000, () => {
  console.log('server start http://localhost:3000/')
})